package com.lmz.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmz.common.TO.mq.OrderTo;
import com.lmz.common.TO.mq.StockDetailTo;
import com.lmz.common.TO.mq.StockLockedTo;
import com.lmz.common.TO.skuHasStockVo;
import com.lmz.common.exception.NoStockException;
import com.lmz.common.utils.PageUtils;
import com.lmz.common.utils.Query;
import com.lmz.common.utils.R;
import com.lmz.ware.dao.WareSkuDao;
import com.lmz.ware.entity.WareOrderTaskDetailEntity;
import com.lmz.ware.entity.WareOrderTaskEntity;
import com.lmz.ware.entity.WareSkuEntity;
import com.lmz.ware.feign.orderFeignService;
import com.lmz.ware.feign.productFeignService;
import com.lmz.ware.service.WareOrderTaskDetailService;
import com.lmz.ware.service.WareOrderTaskService;
import com.lmz.ware.service.WareSkuService;
import com.lmz.ware.vo.OrderItemVo;
import com.lmz.ware.vo.OrderVo;
import com.lmz.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private productFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WareOrderTaskService orderTaskService;
    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    private orderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //如果没有库存记录则为新增，若有则是修改
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //远程查询sku的名字
            try {
                //有异常无需回滚
                R info = productFeignService.info(skuId);
                Map<String, Object> map = (Map<String, Object>) info.get("skuInfo");
                String skuName = (String) map.get("skuName");
                wareSkuEntity.setSkuName(skuName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.baseMapper.insert(wareSkuEntity);
        } else {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<skuHasStockVo> getSkusStock(List<Long> skuIds) {
        List<skuHasStockVo> collect = skuIds.stream().map(skuId -> {
            skuHasStockVo skuHasStockVo = new skuHasStockVo();
            Long count = this.baseMapper.getSkuStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count != null && count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 为某个订单锁定库存
     * 运行时异常都会回滚
     * <p>
     * 解锁场景：
     * 1.订单成功生成，但是没有进行支付被取消
     * 2.库存锁定成功但是其他业务失败导致订单回滚，之前锁定的库存需要进行解锁
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //保存库存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        //找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询在哪里有库存
            List<Long> wareId = this.baseMapper.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareId);
            return stock;
        }).collect(Collectors.toList());

        //锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStock = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                //成功返回记录数为1，否则为0
                Long count = this.baseMapper.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    skuStock = true;
                    //设置库存锁定相关的表信息
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(
                            null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    orderTaskDetailService.save(taskDetailEntity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, stockDetailTo);
                    lockedTo.setDetail(stockDetailTo);
                    //库存锁定成功，给MQ发送消息
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                    break;
                } else {
                    //当前仓库锁定失败
                }
            }
            if (!skuStock) {
                throw new NoStockException(skuId);
            }
        }
        //此时全部锁定成功
        return true;
    }

    @Override
    public void unLockStockWare(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        //先查寻数据库关于这个订单的锁定库存的信息
        //若没有信息，则库存锁定失败，库存回滚了，则不需要解锁库存，否则需要解锁库存
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId != null) {
            //拿到订单号去查询当前订单是否成功
            Long id = to.getId(); //库存工作单id
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo data = r.getData("data", new TypeReference<OrderVo>() {
                });
                //需要进行解锁
                if (data == null || data.getStatus() == 4) {
                    //订单取消状态才能解锁
                    if (byId.getLockStatus() == 1) {
                        //只要是锁定状态下才能解锁
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getTaskId());
                    }
                }
            } else {
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    //防止订单服务卡顿导致订单状态一直不能进行修改
    @Transactional
    @Override
    public void unLockStockOrder(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //检测库存是否已经被解锁，防止重复解锁
        WareOrderTaskEntity task = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        //按照库存工作单的id找到所有未解锁的库存进行解锁
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity taskDetailEntity : list) {
            unLockStock(taskDetailEntity.getSkuId(),
                    taskDetailEntity.getWareId(),
                    taskDetailEntity.getSkuNum(),
                    taskDetailEntity.getId());
        }
    }

    /**
     * 解锁库存
     */
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        this.baseMapper.unLockStock(skuId, wareId, num);
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2); //变为已解锁
        orderTaskDetailService.updateById(entity);
    }


    @Data
    private class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}